﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Decisions.HL7.DataTypes
{
    public class NM : AbstractDataType
    {
        public int? ValueAsInt { get; set; }

        public long? ValueAsLong { get; set; }

        public decimal? ValueAsDecimal { get; set; }

        public override void Parse(string value, HL7ParserOptions options, string dataName, char? whichSep)
        {

            if (string.IsNullOrEmpty(value.Trim())) {
                // Leave all values as null and return;
                return;
            }

            if (value.IndexOf('.') > -1)
            {
                ParseAsDecimal(value, dataName);
                return;
            }
            else {
                ParseAsLong(value, dataName);
                return;
            }
        }

        private void ParseAsLong(string value, string dataName)
        {
            long outValue;
            if (long.TryParse(value, out outValue))
            {
                ValueAsDecimal = outValue;
                ValueAsLong = outValue;
                ValueAsInt = (int)outValue;
            }
            else
            {
                // @TODO respect non strict parsing mode.
                throw new Exception(dataName + " could not be parsed due to an error");
            }
        }

        private void ParseAsDecimal(string value, string dataName)
        {
            decimal outValue;
            if (decimal.TryParse(value, out outValue))
            {
                ValueAsDecimal = outValue;
                ValueAsLong = (long)outValue;
                ValueAsInt = (int)outValue;
            }
            else {
                // @TODO respect non strict parsing mode.
                throw new Exception(dataName + " could not be parsed due to an error");
            }
        }


        public override string GetER7(HL7ParserOptions options)
        {
            return ValueAsDecimal != null ? ValueAsDecimal.ToString() : null;
        }
    }
}
